package br.fot.granola.oboe.graphics.camera;

import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLU;
import br.fot.granola.oboe.graphics.Node;

public class CameraGL10Backend implements CameraBackend
{
	public CameraGL10Backend()
	{
	}
	
	public void draw( Node frontc, GL10 gl )
	{
		Camera front = (Camera) frontc;
		if( front.clearColor != null )
		{
			gl.glClearColor( front.clearColor.r, front.clearColor.g, front.clearColor.b, front.clearColor.a );  // OpenGL docs.
			gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);		
		}
		else
		{
			gl.glClear( GL10.GL_DEPTH_BUFFER_BIT );		
		}
		
		gl.glLoadIdentity();
		gl.glTranslatef( -front.position.x, -front.position.y, -front.position.z );

		gl.glRotatef( front.rotation.x, 1, 0, 0);
		gl.glRotatef( front.rotation.y, 0, 1, 0);
		gl.glRotatef( front.rotation.z, 0, 0, 1);
		
		for( Node n : front.parentScene.children )
		{
			gl.glPushMatrix();
			n.getBackend().draw( n, gl );
			gl.glPopMatrix();
		}
	}

	public void created( Node frontc, GL10 gl )
	{
		Camera front = (Camera) frontc;
		// Set the background color to black ( rgba ).
		gl.glClearColor( front.clearColor.r, front.clearColor.g, front.clearColor.b, front.clearColor.a );
		
		// Enable Smooth Shading, default not really needed.
		gl.glShadeModel(GL10.GL_SMOOTH);
		
		// Depth buffer setup.
		gl.glClearDepthf(1.0f);
		
		// Enables depth testing.
		gl.glEnable(GL10.GL_DEPTH_TEST);
		
		// The type of depth testing to do.
		gl.glDepthFunc(GL10.GL_LEQUAL);
		
		// Really nice perspective calculations.
		gl.glHint( GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST );		
	}
	
	public void viewChanged( Node frontc, GL10 gl, int width, int height )
	{
		Camera front = (Camera) frontc;
		// Sets the current view port to the new size.
		gl.glViewport(0, 0, width, height);// OpenGL docs.
		// Select the projection matrix
		gl.glMatrixMode(GL10.GL_PROJECTION);// OpenGL docs.
		// Reset the projection matrix
		gl.glLoadIdentity();// OpenGL docs.
		// Calculate the aspect ratio of the window
		GLU.gluPerspective(gl, front.fov,
                                   (float) width / (float) height,
                                   0.1f, 100.0f);
		// Select the modelview matrix
		gl.glMatrixMode(GL10.GL_MODELVIEW);// OpenGL docs.
		// Reset the modelview matrix
		gl.glLoadIdentity();// OpenGL docs.		
	}	
}
